package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.shopping.constants.GlobalConstants;
import com.cskaoyan.shopping.converter.ContentConverter;

import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.PanelContentMapper;
import com.cskaoyan.shopping.dal.persistence.PanelMapper;
import com.cskaoyan.shopping.dto.HomePageResponse;
import com.cskaoyan.shopping.dto.PanelContentItemDto;
import com.cskaoyan.shopping.dto.PanelDto;
import com.cskaoyan.shopping.service.IHomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: 周子伟
 * @description ${主页显示}
 * @date: 2022/7/29 16:32
 */
  /*
         显示首页商品信息，显示的是Panel信息，但是这里注意下，如何获取Panel信息呢？
         1. 先调用 PanelMapper selectPanelContentById，自己看下sql语句，获取 List<Panel>
         2. Panel对象中，少了 List<PanelContentItem> panelContentItems
         3. 因此，需要遍历List中的Panel，在调用PanelContentMapper 的 selectPanelContentAndProductWithPanelId方法
            获取List<PanelContentItem>，利用MapStruct将其转化为 List<PanelContentItemDto>
         4. 然后set 到Panel

     */
@Service
public class IHomeServiceImpl implements IHomeService {
    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ContentConverter contentConverter;

    @Override
    public HomePageResponse homepage() {

        HomePageResponse response = new HomePageResponse();

        try {


            HashSet<PanelDto> panelDtos = new HashSet<>();
          //  List<Panel> panelList = panelMapper.selectPanelContentById(null);
            List<Panel> panelList= panelMapper.selectAllPanelContentById();
            System.out.println(panelList);

            for (int i = 0; i < panelList.size(); i++) {

                Panel panel = panelList.get(i);
                List<PanelContentItem> panelContentItems = panelContentMapper.
                        selectPanelContentAndProductWithPanelId(panel.getId());
                PanelDto panelDto = contentConverter.panel2Dto(panel);
                List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems);

                panelDto.setPanelContentItems(panelContentItemDtos);
                panelDtos.add(panelDto);

            }


            response.setPanelContentItemDtos(panelDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        }catch (Exception e){

            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;


    }
}
